package com.granada.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;



/**
 *获取到session_key的工具类
 */
@Slf4j
public class AuthUtil {
    public static final String APPID = "wx9ffcbe21dac328fd";
    public static final String APPSECRET = "93a5f5e79a4211608faf4ac8f916e1e7";

    /**
     * @Title: getAccessToken
     * @Description: 获取接口调用凭证
     * @param: @return
     * @return: String
     */
    public static JSONObject getAccessToken(String code) {
        RestTemplate restTemplate = new RestTemplate();
        StringBuffer sb = new StringBuffer("https://api.weixin.qq.com/sns/jscode2session?appid=");
        sb.append(AuthUtil.APPID);
        sb.append("&secret=");
        sb.append(AuthUtil.APPSECRET);
        sb.append("&js_code=");
        sb.append(code);
        sb.append("&grant_type=authorization_code");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(sb.toString(), HttpMethod.GET, entity, String.class);
        String body = responseEntity.getBody();
        // 返回结果转换为json对象
        JSONObject jObject = JSONObject.parseObject(body);
        return jObject;
    }
}